import React, { useEffect, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

interface MarkdownIframeProps {
    content: string;
}

const MarkdownIframe: React.FC<MarkdownIframeProps> = ({ content }) => {
    const iframeRef = useRef<HTMLIFrameElement>(null);
    const [height, setHeight] = useState(0);

    useEffect(() => {
        if (iframeRef.current) {
            const iframe = iframeRef.current;
            const doc = iframe.contentDocument;

            if (doc) {
                doc.open();
                doc.write(`
                    <html>
                        <head>
                            <style>
                                body {
                                    font-family: sans-serif;
                                    color: white;
                                    background-color: #0f172a;
                                    padding: 16px;
                                    line-height: 1.6;
                                    margin: 0;
                                }
                                h1 { font-size: 2em; margin: 0.67em 0; }
                                h2 { font-size: 1.5em; margin: 0.75em 0; }
                                h3 { font-size: 1.2em; margin: 0.85em 0; }
                                p { margin: 0.5em 0; }
                                a { color: #60a5fa; text-decoration: underline; }
                                code { background-color: #1e293b; color: #facc15; padding: 2px 4px; border-radius: 4px; }
                                pre { background-color: #1e293b; color: #f0f0f0; padding: 12px; border-radius: 6px; overflow-x: auto; }
                                table { border-collapse: collapse; margin: 1em 0; }
                                th, td { border: 1px solid #374151; padding: 6px 12px; }
                                blockquote { border-left: 4px solid #64748b; padding-left: 12px; color: #cbd5e1; margin: 1em 0; }
                                ul { padding-left: 1.2em; list-style-type: disc; }
                                ol { padding-left: 1.2em; list-style-type: decimal; }
                            </style>
                        </head>
                        <body>
                            <div id="root"></div>
                            <script>
                                function updateHeight() {
                                    const height = document.body.scrollHeight;
                                    window.parent.postMessage({ type: 'setHeight', height }, '*');
                                }
                                window.addEventListener('load', updateHeight);
                                window.addEventListener('resize', updateHeight);
                            </script>
                        </body>
                    </html>
                `);
                doc.close();

                const root = doc.getElementById("root");
                if (root) {
                    import("react-dom").then(ReactDOM => {
                        ReactDOM.render(
                            <ReactMarkdown remarkPlugins={[remarkGfm]}>
                                {content || ""}
                            </ReactMarkdown>,
                            root,
                            () => {
                                // 渲染完成后通知父页面更新高度
                                const height = doc.body.scrollHeight;
                                setHeight(height);
                            }
                        );
                    });
                }
            }
        }

        // 监听 iframe 发送的消息
        const handleMessage = (event: MessageEvent) => {
            if (event.data?.type === "setHeight" && typeof event.data.height === "number") {
                setHeight(event.data.height);
            }
        };
        window.addEventListener("message", handleMessage);

        return () => {
            window.removeEventListener("message", handleMessage);
        };
    }, [content]);

    return (
        <iframe
            ref={iframeRef}
            title="Markdown Content"
            style={{ width: "100%", height: `${height}px`, border: "none" }}
        />
    );
};

export default MarkdownIframe;
